<cfcomponent>

	<cfscript>
		this.name = "Scholars";
		this.applicationTimeout = CreateTimeSpan(0,7,0,0); // 7 days
		this.loginStorage = "cookie";
		// client management
		// this.clientManagement = true;
		// session management
		// this.sessionManagement = true;
		// this.sessionTimeout = CreateTimeSpan(0,1,0,0); // 1 day
		// this.mappings is a struct
		// this.mappings["/assets"] = "C:\inetpub\assets";
		// this.mappings["/validateThis"] = "C:\inetpub\assets\validateThis";
	</cfscript>
	
	<cffunction name="onApplicationStart" output="no" access="public" returntype="boolean">
		<cfscript>
			if (cgi.HTTP_HOST eq "calgrants"){
				application.mode = "dev";
				
			} else {
				application.mode = "prod";
			}
			application.datasource = "wms";
			application.pathToApplication = "/applications/scholarships";
			application.pathToJQuery = "/assets/jquery/jquery.min.js";
			application.pathToJQueryUI = "/assets/jquery/jquery-ui.min.js";
			application.pathToKendo = "/assets/kendoui/js/kendo.all.min.js";
			application.pathToKendoDefaultCSS = "/assets/kendoui/styles/kendo.default.min.css";
			application.pathToKendoCommonCSS = "/assets/kendoui/styles/kendo.common.min.css";
			application.pathToBootstrap = "/assets/bootstrap/js/bootstrap.min.js";
			application.pathToBootstrapCSS = "/assets/bootstrap/css/bootstrap.min.css";
			application.pathToJQueryTubeplayer = "/assets/jquery.tubeplayer/jQuery.tubeplayer.js";
			application.pathToComponents = "assets.calgrants.com";
			application.pathToBO = application.pathToComponents & ".bo";
			application.pathToServices = application.pathToComponents & ".service";
			application.pathToGateways = application.pathToComponents & ".gateway";
			application.pathToUI = "/assets/calgrants/ui";
			application.pathToTemplates = "/assets/calgrants/ui/templates";
			application.apiUrl = "/assets/calgrants/com/API.cfc";
			//application.wrapperUrl = "/wseval/";
			application.personality = {};
			application.personality.name = "Cash for College";
			application.personality.email = "cashforcollege@csac.ca.gov";
			application.personality.bcc = "cash4collegeca@gmail.com";
			application.personality.phone = "916-464-6410";
			application.developer = {};
			application.developer.name = "Syntric";
			application.developer.email = "support@syntric.com";
			application.developer.phone = "916-776-6650";
			application.fulfillment = {};
			application.fulfillment.name = "ECMC";
			application.fulfillment.email = "publications@ecmc.org";
			application.payment = {};
			application.payment.name = "Los Angeles Area Chamber of Commerce";
			application.payment.email = "cashforcollege@lachamber.com";
			//application.currentProgramYear = "2014-2015";
			application.initDateTime = now();
            initValidator();
			return true;
		</cfscript>
	</cffunction>
	
	<cffunction name="onRequestStart">
		<cfscript>
			var relocation = false;
			if (cgi.https eq "off") {
				relocation = true;
			}
			if (StructKeyExists(url, "logout") or StructKeyExists(form, "logout")) {
				logout();
				relocation = true;
			}
			if (StructKeyExists(url, "initApp") or StructKeyExists(form, "initApp")) {
				ApplicationStop();
				relocation = true;
			}
		</cfscript>
		<!--- https check
		<cfif cgi.HTTPS eq "off">
			<cfset relocation = true />
		</cfif> --->
		<!--- logout
		<cfif IsDefined("logout")>
			<cflogout />
			<cflocation url="https://#cgi.SERVER_NAME##cgi.SCRIPT_NAME#" addtoken="no">
		</cfif> --->
		<!--- restart application
		<cfif StructKeyExists(url, "initApp")>
			<cfset ApplicationStop() />
			<cflocation url="https://#cgi.SERVER_NAME##cgi.SCRIPT_NAME#" addtoken="no">
		</cfif> --->
		<!--- <cfif relocation eq true>
			<cflocation url="https://#cgi.SERVER_NAME##cgi.SCRIPT_NAME#" addtoken="no">
		</cfif> --->
		<cflock scope="application" timeout="20" type="readonly">
			<cfset StructAppend(request, application) />
		</cflock>
		<cfset request.alerts = ArrayNew(1) />		
		<cflogin>
			<cfif IsDefined("cflogin") and StructKeyExists(cflogin, "name") and StructKeyExists(cflogin, "password")>
				<cfscript>
					var scholarshipGateway = new assets.calgrants.com.gateway.ScholarshipGateway();
					var scholar = scholarshipGateway.query(Email = cflogin.name, Password = cflogin.password);
				</cfscript>
				<cfif scholar.RecordCount eq 1 and scholar.Deleted eq 0 and IsDate(scholar.Claim_Date)>
					<cfloginuser name="#scholar.Scholarship_ID#" password="" roles="Scholar" />
				<cfelse>
					<cfset ArrayAppend(request.alerts, "Login Failed\n\nCheck your Email and Password. Contact #request.payment.name# at #request.payment.email# for assistance.") />
				</cfif>
			</cfif>
			<cfif IsDefined("form.Claim_ID") AND Len(Trim(form.Claim_ID)) gt 8>
				<cfscript>
					var scholarshipGateway = new assets.calgrants.com.gateway.ScholarshipGateway();
					var scholar = scholarshipGateway.query(Claim_ID = Trim(form.Claim_ID));
					var storedProcedureGateway = new assets.calgrants.com.gateway.StoredProcedureGateway();
					var qCurrentCohort = storedProcedureGateway.call(sp = "getCurrentCohort");
					var currentCohort = qCurrentCohort.currentCohort;
				</cfscript>
				<!--- Valid claim --->
				<cfif scholar.RecordCount eq 1 and NOT IsDate(scholar.Claim_Date) and scholar.Cohort eq currentCohort and scholar.Deleted eq 0>
					<cfloginuser name="#scholar.Scholarship_ID#" password="" roles="Claimant" />
				<!--- Already claimed --->
				<cfelseif scholar.RecordCount eq 1 and IsDate(scholar.Claim_Date) and scholar.Deleted eq 0>
					<cfset ArrayAppend(request.alerts, "Scholarship Claimed\n\nScholarship is already claimed.  Login with your Email and Password instead. Contact #request.payment.name# at #request.payment.email# for assistance.") />
				<!--- Scholarship is expired --->
				<cfelseif scholar.RecordCount eq 1 and scholar.Cohort neq currentCohort and scholar.Deleted eq 0>
					<cfset ArrayAppend(request.alerts, "Scholarship Expired\n\nScholarship is expired and cannot be claimed. Contact #request.payment.name# at #request.payment.email# for assistance.") />
				<!--- Claim_ID is not valid --->
				<cfelseif scholar.RecordCount eq 0>
					<cfset ArrayAppend(request.alerts, "Invalid Claim ID\n\nThe Claim ID entered is invalid.  Check your scholarship award letter and try again. Contact #request.payment.name# at #request.payment.email# for assistance.") />
				<!--- Other invalid conditions --->
				<cfelse>
					<cfset ArrayAppend(request.alerts, "Failed Claim\n\nSomething went wrong validating your Claim ID. Contact #request.payment.name# at #request.payment.email# for assistance.") />
				</cfif>
			</cfif>
		</cflogin>
		<cfif NOT IsUserLoggedIn()>
			<cfinclude template="login.cfm" />
			<cfabort>
		<cfelse>
			<cfscript>
				if (NOT IsDefined("scholar")) {
					var scholarshipGateway = new assets.calgrants.com.gateway.ScholarshipGateway();
					var scholar = scholarshipGateway.query(Scholarship_ID = GetAuthUser());
				}
			</cfscript>
			<cfset request.scholar = StructNew() />
			<cfloop index="col" list="#scholar.ColumnList#">
				<cfset request.scholar[col] = scholar[col][1] />
			</cfloop>
			<cfif GetUserRoles() eq "Claimant">
				<cfinclude template="login.cfm" />
				<cfabort>
			</cfif>
		</cfif>
	</cffunction>
	
	<cffunction name="onError">
		<cfargument name="Exception" required="true" />
		<cfargument name="EventName" required="true" />
		<cfif application.mode eq "prod">
			<cfmail to="kenhobbs@gmail.com" from="kenhobbs@gmail.com" subject="Scholars Error" type="html">
				<cfdump var="#arguments.Exception#" expand="yes" label="Exception" />
				<cfdump var="#cgi#" expand="yes" label="CGI" />
				<cfdump var="#form#" expand="yes" label="Form" />
				<cfdump var="#url#" expand="yes" label="URL" />
			</cfmail>
		<cfelse>
			<cfdump var="#arguments.Exception#" expand="yes" label="Exception" />
			<cfdump var="#cgi#" expand="no" label="CGI" />
			<cfdump var="#form#" expand="no" label="Form" />
			<cfdump var="#url#" expand="no" label="URL" />
		</cfif>
		<h1>Ooops</h1>
		<p>The application has encountered an error.  An error message has been sent to the developer.</p>
		<p>If you require immediate assistance with this error, please <a href="mailto:support@syntric.com">contact the developer</a>.</p>
		<cfabort>
	</cffunction>
	
	<cffunction name="onRequestEnd">
        <cfsetting showdebugoutput="no">
    </cffunction>
	
	<cffunction name="logout" access="private" returntype="void">
		<cflogout />
		<cfreturn />
	</cffunction>
	
	<!--- <cffunction name="loginScholar" access="private" returntype="void">
		<cfargument name="Scholarship_ID" type="number" required="yes" />
		<cfloginuser name="#arguments.Scholarship_ID#" password="" roles="Scholar" />
	</cffunction>
	
	<cffunction name="isValidHost" access="private" returntype="boolean">
		<cfscript>
			var retVal = false;
				(
				Left(form.Claim_ID, 1) eq "P" or Left(form.Claim_ID, 1) eq "W") AND
				IsValid(integer, Right(form.Claim_ID, (Len(form.Claim_ID) - 1)));
			
			if (ListFind(cgi.HTTP_REFERER, "www.calgrants.org", "/") gt 0 or ListFind(cgi.HTTP_REFERER, "calgrants.org", "/") gt 0 or cgi.HTTP_HOST eq "calgrants") {
				retVal = true;
			}
			return retVal;
		</cfscript>
	</cffunction> --->

    <cffunction name="initValidator">
        <cfscript>
            lock scope="application" timeout="20" type="readonly" {
                var validatorConfig = {extraRuleValidatorComponentPaths = "/assets/calgrants/com/validators/", definitionPath = "/assets/calgrants/com/bo/"};
                application.validator = new validateThis.ValidateThis(validatorConfig);
            }
        </cfscript>
    </cffunction>

</cfcomponent>